package server;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class DBAccess 
{
//	private static final String HOST_NAME = "mysqlsrv.cs.tau.ac.il";
//	private static final String DB_NAME = "dankilma";
//	private static final String USERNAME = "dankilma";
//	private static final String PASSWORD = "acquire-db";

    private static final String HOST_NAME = "localhost";
    private static final String DB_NAME = "acquire";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123";
    
    Connection m_objConnection;
	Statement m_objStatement;
	
	public boolean InitDBConnection()
	{
		boolean blnConnectionEstablished = false;
		
		try
		{
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			String url = "jdbc:mysql://" + HOST_NAME + ":3306/" + DB_NAME;
			m_objConnection = DriverManager.getConnection(url, USERNAME, PASSWORD);
			blnConnectionEstablished = true;
			
			m_objStatement = m_objConnection.createStatement();
		}
		catch (Exception e)
		{
			if (blnConnectionEstablished)
			{
				try 
				{
				    m_objConnection.close();
				} 
				catch (SQLException e1) 
				{					
					e1.printStackTrace();
				}
			}
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public void ShutDBConnection()
	{
		try 
		{
			m_objStatement.close();		
			m_objConnection.close();
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
	}

	public ResultSet ReadFromDB(String p_strQuery)
	{
		try 
		{
			return m_objStatement.executeQuery(p_strQuery);
		} 
		catch (SQLException e)
		{		
			e.printStackTrace();
			return null;
		}
	}
	
		
	public int WriteToDB(String p_strUpdate)
	{
		try
		{
			return m_objStatement.executeUpdate(p_strUpdate);
		}
		catch (SQLException e)
		{		
			e.printStackTrace();
			return -1;
		}	
	}
}
